import json
from collections import defaultdict
import os
from datetime import datetime, time
import configparser
CONFIG_FILE = 'config.ini'
def save_settings(total_num,win_cnt):
        config = configparser.ConfigParser()
        config.read(CONFIG_FILE)
        # 创建配置部分
        config['SETTINGS'] = {
            'total_money': config.get('SETTINGS', 'total_money', fallback='5000'),
            'init_money': config.get('SETTINGS', 'init_money', fallback='2'),
            'run_time': config.get('SETTINGS', 'run_time', fallback='24'),
            'ip': config.get('SETTINGS', 'ip', fallback='c145902.sys998.com'),
            'cookie_value': config.get('SETTINGS', 'cookie_value', fallback=''),
            'refresh_time': config.get('SETTINGS', 'refresh_time', fallback='180'),
            'trigger_count': config.get('SETTINGS', 'trigger_count', fallback='1'),
            'profit_money': config.get('SETTINGS', 'profit_money', fallback='5000'),
            'choose_number': config.get('SETTINGS', 'choose_number', fallback='0:9,1:3,2:5,3:7,4:1,5:9,6:3,7:5,8:7,9:1'),
            'start_count': config.get('SETTINGS', 'start_count', fallback='20'),
            'total_num': str(total_num),
            'win_cnt': str(win_cnt),
            'right_now': config.get('SETTINGS', 'right_now', fallback='0'),
            'direct': config.get('SETTINGS', 'direct', fallback='<')
        }
        # 写入配置文件
        with open(CONFIG_FILE, 'w') as configfile:
            config.write(configfile)

def analyze_lottery_data(dir_path,file_name,choose_number):
    """主函数：按日期分析彩票数据并为每天生成HTML报告"""
    today = datetime.now().strftime("%Y-%m-%d")
    full_path = os.path.join(dir_path, file_name)

    if not os.path.exists(full_path):
        print(f"错误：文件 {full_path} 不存在！")
        return

    try:
        with open(full_path, 'r', encoding='utf-8') as f:
            data = json.load(f)['items']
    except json.JSONDecodeError:
        print(f"错误：无法解析JSON文件 {full_path}！")
        return
    except Exception as e:
        print(f"错误：读取文件时发生异常 - {str(e)}")
        return

    daily_data = defaultdict(list)
    for item in data:
        try:
            open_time = item['open_time']
            date = open_time.split(' ')[0]
            daily_data[date].append(item)
        except KeyError:
            print("警告：数据项缺少open_time字段，跳过该条目")
            continue

    for date, items in daily_data.items():
        if today != date:
            continue
        if len(items) < 2:
            print(f"日期 {date} 的数据不足，跳过...")
            continue
        try:
            sorted_items = sorted(items, key=lambda x: int(x['issue_no']))
        except (KeyError, ValueError):
            print(f"警告：日期 {date} 的期号格式异常，跳过该日期")
            continue

        daily_analysis = analyze_daily_data(sorted_items, date,choose_number)
        data = daily_analysis["results"]
        total_cnt = len(data)
        total_hits = daily_analysis["total_hits"]
        save_settings(total_cnt,total_hits)
        print(f"{total_cnt}------------->{total_hits}")
        



def analyze_daily_data(items, date,choose_number):
    """分析单日彩票数据"""
    analysis_result = []
    rule_map = {}
    for pair in choose_number.split(','):
        if ':' in pair:
            key_str, value_str = pair.split(':')
        try:
            key = int(key_str.strip())
            value = int(value_str.strip())
            rule_map[key] = value
        except ValueError:
            # 处理转换错误
            print(f"忽略无效的键值对: {pair}")
    """单"""
    consecutive_zero_hits = 1

    for i in range(len(items) - 1):
        current_item = items[i]
        next_item = items[i + 1]
        next_open_time = next_item.get('open_time', '时间缺失')

        try:
            current_first = int(current_item['open_code'].split(',')[0])
        except (IndexError, ValueError):
            print(
                f"警告：日期 {date}，期号 {current_item['issue_no']} 的open_code格式异常，跳过")
            continue

        try:
            target_number = rule_map[current_first]
        except KeyError:
            print(f"警告：日期 {date}，号码 {current_first} 不在规则映射中，跳过")
            continue

        try:
            next_codes = list(map(int, next_item['open_code'].split(',')))
        except (IndexError, ValueError):
            print(f"警告：日期 {date}，期号 {next_item['issue_no']} 的open_code格式异常，跳过")
            continue

        hit_count = sum(1 for num in next_codes if num == target_number)

        analysis_result.append({
            "current_issue": current_item['issue_no'],
            "next_issue": next_item['issue_no'],
            "next_open_time": next_open_time,
            "current_first": current_first,
            "target_number": str(target_number),
            "next_code": next_item['open_code'],
            "hit_count": hit_count,
            "consecutive_zero_hits": consecutive_zero_hits
        })

        if hit_count == 0:
            consecutive_zero_hits += 1
        else:
            consecutive_zero_hits = 1

    # 计算总命中次数
    total_hits = sum(item['hit_count'] for item in analysis_result)

    # 按目标号码统计命中次数
    target_hits = defaultdict(int)
    for item in analysis_result:
        target_hits[item['target_number']] += item['hit_count']

    return {
        "results": analysis_result,
        "total_hits": total_hits,
        "target_hits": target_hits
    }
if __name__ == "__main__":
    print("开始按日期分析彩票数据...")
    analyze_lottery_data()
    print("所有日期分析完成！")